package com.yindian.cos.easy.security.authentication.login.social.weibo;

import com.yindian.cos.easy.security.authentication.login.social.core.*;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.AuthenticationException;
import com.yindian.cos.easy.security.handler.AuthenticationFailureHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微博登录回调
 *
 * @author zhangchuanhao
 * @create 2018/11/19
 */
@Log4j2
@RestController
public class WeiBoController {

    @Qualifier("weiBoAccessTokenFactory")
    @Autowired(required = false)
    private AbstractAccessTokenFactory weiBoAccessTokenFactory;

    @Qualifier("weiBoUserInfoFactory")
    @Autowired(required = false)
    private AbstractUserInfoFactory<WeiBoUserInfo> weiBoUserInfoFactory;

    @Autowired(required = false)
    private AbstractPostProcessor abstractPostProcessor;

    @Autowired(required = false)
    private AuthenticationFailureHandler authenticationFailureHandler;

    @RequestMapping("${easy.security.authorization.weibo.redirect-uri:/social/weibo/notify}")
    public void weibo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String code = request.getParameter("code");

            AccessToken accessToken = weiBoAccessTokenFactory.getAccessToken(code);
            WeiBoUserInfo weiBoUserInfo = weiBoUserInfoFactory.getUserInfo(accessToken);
            UserInfo userInfo = new UserInfo(
                    ProviderName.WEIBO,
                    accessToken.getOpenId(),
                    weiBoUserInfo.getScreen_name(),
                    weiBoUserInfo.getProfile_image_url(),
                    accessToken.getAccessToken()
            );
            log.debug("{}登录进入授权回调处理，userInfo = {}", userInfo.getProvider(), userInfo);
            if (abstractPostProcessor != null) {
                abstractPostProcessor.processor(request, response, userInfo);
            }
        } catch (AuthenticationException ex) {
            authenticationFailureHandler.handler(request, response, ex);
        }
    }
}

